import { resolve } from 'node:path'
import { fileURLToPath, URL } from 'node:url'

import { AliasOptions, defineConfig, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  let config: UserConfig = {}

  const alias: AliasOptions = {
    '@shared': fileURLToPath(new URL('./src/shared', import.meta.url)),
    '@option': fileURLToPath(new URL('./src/option', import.meta.url)),
    '@background': fileURLToPath(new URL('./src/background', import.meta.url))
  }

  if (mode === 'options') {
    config = {
      base: './',
      root: resolve(__dirname, `src/${mode}`),
      publicDir: resolve(__dirname, `src/${mode}/public`),
      plugins: [vue()],
      resolve: { alias },
      define: {
        __VUE_OPTIONS_API__: 'false'
      },
      build: {
        outDir: resolve(__dirname, `dist/${mode}`),
        rollupOptions: {
          input: {
            popup: resolve(__dirname, `src/${mode}/index.html`)
          }
        }
      }
    }
  }

  if (mode === 'background' || mode === 'content') {
    config = {
      mode: 'production',
      resolve: { alias },
      build: {
        minify: false,
        emptyOutDir: false,
        outDir: resolve(__dirname, 'dist'),
        lib: {
          entry: resolve(__dirname, `src/${mode}/index.ts`),
          formats: ['es'],
          fileName: () => `${mode}.js`
        }
      }
    }
  }

  return config
})
